﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FourthWallProject.GameObjects.GameComponents;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.IO;

namespace FourthWallProject.GameObjects
{
    static class LevelLoader
    {
        private static Game _game;
        internal static GameComponents.LevelGrid LoadLevel(string levelPath, Game game)
        {
            texture = game.Content.Load<Texture2D>("Images/Block");
            textureFloor = game.Content.Load<Texture2D>("Images/pinguplattform");
            _game = game;
            using (Stream fileStream = TitleContainer.OpenStream("Content/Levels/" + levelPath + ".txt"))
            {
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    int width;
                    List<string> lines = new List<string>();
                    
                    string line = reader.ReadLine();
                    width = line.Length;
                    while (line != null)
                    {
                        lines.Add(line);
                        if (line.Length != width)
                            throw new Exception(String.Format("The length of line {0} is different from all preceeding lines.", lines.Count));
                        line = reader.ReadLine();
                    }

                    var levelgrid = new LevelGrid(width, lines.Count(),game);
                    for (int y = 0; y < lines.Count(); y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            char c = lines[y][x];
                            levelgrid.AddTile(x,y,GetTile(c));
                        }                        
                    }
                    return levelgrid;
                }
            }
        }

        static Texture2D texture;
        static Texture2D textureFloor;
        private static StaticGameTile GetTile(char p)
        {
            switch (p.ToString().ToUpper())
            {
                case "X":
                    return new StaticGameTile(texture, new Rectangle(), Color.White, SolidState.Solid,_game);
                case "-":
                    return new StaticGameTile(textureFloor, new Rectangle(), Color.White, SolidState.Solid, _game);
                //case "S":
                //    GameState.Character.Position = new Vector2(GameState.Character.)
                //    break;
                case "E":
                    return new StaticGameTile(texture, new Rectangle(), Color.Brown, SolidState.End,_game);
                case "O":
                    return null;
                default:
                    return null;
            }
        }
    }
}
